from pymongo import MongoClient
import tornado.httpserver
import tornado.ioloop
import tornado.web
from bson import json_util
class BaseHandler(tornado.web.RequestHandler):
    def initialize(self):
        self.db = self.settings['db']
        self.set_header('Content-Type','application/json;charset=UTF-8')

class XmppBaseHandler(tornado.web.RequestHandler)：
    def initialize(self):
    	self.set_header('Content-Type','text/xml;charset=UTF-8')
        
#查询的接口        
class MYCPRTHandler(BaseHandler):
	@tornado.web.removeslash
    def get(self, s_key):
        doc = {'name':'0', 'descripts':'', 'count':0}
        s_key = s_key.upper()
        id,name, descripts, price, age ='', '', '', '', ''
        #获取url的http://www.test.com/&name=太子&id=1314 的值
        name = self.get_argument('name', default='', strip=True)
        id = self.get_argument('id', default='', strip=True)
        ret_info = self.get_argument('ret',default='simple',strip=True)
        #获取不是key-value形式的url参数  如：http://www.test.com/2014  参数为‘2014’ 或者http://www.test.com/电影-狸猫换太子
        if s_key:
            if re.search("^[A-Z0-9]{4}$", s_key):
                age = s_key
            elif re.search("^(?P<integerPart>\d{1,7})(\.)?(?P<decimalPart>(?(2)\d{1,2}))$", s_key):
                price = s_key
            else:
                s = s_key.split('-')
                descripts = s[0]
                if len(s) > 1: name = s[1]
                       
            
        query = {'id': 'xxx'}
        fields = ['name', 'descripts','price', 'age']
        if ret_info == 'full': fields = None
        
        #去掉多余的/ id查询 如http://www.test.com/123/123/123 变成id=123123123
        if id:
            id = id.replace('/', '')
            query={'id': id}
        elif name != '':
            query={'name': name}
        elif descripts !='':
            query={'descripts': descripts}
        elif name and descripts:
            query={'name': name, 'descripts': descripts}
        elif age:
            query={'age': age}
        
        #查询demo下的test集合    
        message = self.db.test.find(query, fields).sort([('id', 1)])
        doc['data'] = message
        doc['count'] = message.count(True)
        
        ret = json_util.dumps(doc, sort_keys=True, ensure_ascii=False, default=json_util.default, ) #indent=2)
        self.write(ret)


if __name__ == '__main__':
    workers_count = 4
    app_debug = False

    if len(sys.argv) > 1 and sys.argv[1] == 'debug':
        workers_count = 1
        app_debug = True
    
    app = tornado.web.Application([
        (r"/mydemo[/]?(.*)",MYCPRTHandler),
        ], debug = app_debug)

    server = tornado.httpserver.HTTPServer(app)
    server.bind(80)
    server.start(workers_count)
    app.settings['db'] = MongoClient('127.0.0.1', 27017).demo
    tornado.ioloop.IOLoop.instance().start()